package com.app.shop.config.security;


import com.app.shop.util.PwdUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.NoSuchAlgorithmException;


/**
 * SunPasswordEncoder  重写Security密码加密以及密码验证服务
 *
 * @author chenliwei
 * @version 1.0 2017-11-5
 */
@Configuration
public class XSecurityPasswordEncoder implements PasswordEncoder {

    private final static Log logger = LogFactory.getLog(XSecurityPasswordEncoder.class);
    /**
     * Security密码加密
     *
     * @param rawPassword 用户登录密码
     * @return 返回加密后密码
     * @author chenliwei
     */
    @Override
    public String encode(CharSequence rawPassword) {
        String password="";
        try {
            password = PwdUtil.encryptPassword(rawPassword.toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            logger.error("用户登录秘密加密过程中发生异常！");
        }
        return password;
    }

    /**
     * Security登录密码与用户对应验证
     *
     * @param rawPassword     用户页面输入密码
     * @param encodedPassword 数据库中存储用户密码
     * @return 返回密码是否验证通过（通过：true,不通过：false）
     * @author chenliwei
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        boolean bool ;
        System.out.println(encode(rawPassword));
        if (encode(rawPassword).equals(encodedPassword)) {
            logger.debug("用户登录登录成功！");
            bool = true;
        }else{
            logger.debug("用户登录登录失败！"+encodedPassword);
            bool = false;
        }
        return bool;
    }

}
